﻿/**
 * 
 * @author sminutoli
 * resuelve el parseo de un texto, sacandole las cosas "feas" que mete el LoadVars
 * dispara un evento parseFinished si está todo bien y un parseError sino.
 * Hay un par de funciones estáticas que están jamoneras
 * 
 * version 1.0
 * 
 */
import com.dinmax.flash.utilities.communication.TextParserListener;

class com.dinmax.flash.utilities.communication.TextParser {
	
	private var _loader:LoadVars;
	private var textPath:String;
	private var listener:TextParserListener;
	
	function TextParser(textPath:String, listener:TextParserListener) {
		this.setTextPath(textPath);	
		this.setListener(listener);
		
		var root:TextParser = this;
		_loader = new LoadVars();
		_loader.onLoad= function(success:Boolean):Void{
			var text:String=this;
			text = cleanText(parseText(text));
			if(success){
				root.getListener().parseFinished(text);
			} else {
				root.getListener().parseError();
			};
		};
		_loader.load(this.getTextPath());
		
	};
	
	public function getTextPath():String {
		return textPath;
	}

	public function setTextPath(textPath:String):Void {
		this.textPath = textPath;
	}
	
	public function getListener():TextParserListener {
		return listener;
	}

	public function setListener(listener:TextParserListener):Void {
		this.listener = listener;
	}
	
	public static function parseText(text:String):String {
		text=replace(text,"%7C","|");
		text=replace(text,"%20"," ");
		text=replace(text,"%2D","-");
		text=replace(text,"%2E",".");
		text=replace(text,"%3A",":");
		text=replace(text,"%0A","\n");
		text=replace(text,"%22","\"");
		return text;
		
	}
	
	public static function cleanText(text:String):String{
		text = unescape(text);
		return text.substr(0, text.length-24);
	}
	
	public static function replace(text:String,busqueda:String,reemplazo:String):String {
		var lenBusqueda:Number=busqueda.length;
		var lenReemplazo:Number=reemplazo.length;		
		var pos:Number=text.indexOf(busqueda);
		while (pos>-1) {
			text=text.substring(0,pos)+reemplazo+text.substring(pos+lenBusqueda)
			pos=text.indexOf(busqueda);
			
		}
		return text;
	}

}